<template>
  <view class="record-container">
    <!-- 配置选择区 -->
    <view class="config-section" :class="{ 'compact': showKeypad || focusInScoreArea }">
      <view class="config-card">
        <!-- 压缩模式下只显示一行总计 -->
        <view v-if="showKeypad || focusInScoreArea" class="compact-config">
          <text class="compact-text">{{ compactConfigText }}</text>
          <uni-icons type="arrowup" size="16" color="#666" @click="expandConfig"></uni-icons>
        </view>
        
        <!-- 完整配置模式 -->
        <template v-else>
          <view class="config-item" @click="showBowTypePopup">
            <text class="label">弓种</text>
            <view class="value-box">
              <text>{{ bowTypes[bowIndex] }}</text>
              <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
            </view>
          </view>

          <view class="config-item" @click="showDistancePopup">
            <text class="label">距离</text>
            <view class="value-box">
              <text>{{ distances[distIndex] }}</text>
              <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
            </view>
          </view>

          <view class="config-item double">
            <view class="half-item" @click="showTargetSizePopup">
              <text class="label">靶纸</text>
              <view class="value-box">
                <text>{{ targetSizes[targetSizeIndex] }}cm</text>
                <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
              </view>
            </view>
            <view class="half-item" @click="showTargetTypePopup">
              <text class="label">类型</text>
              <view class="value-box">
                <text>{{ targetTypes[targetTypeIndex] }}</text>
                <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
              </view>
            </view>
          </view>

          <view class="config-item double">
            <view class="half-item" @click="showGroupCountPopup">
              <text class="label">组数</text>
              <view class="value-box">
                <text>{{ groupCounts[groupCountIndex] }}</text>
                <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
              </view>
            </view>
            <view class="half-item" @click="showArrowsPerGroupPopup">
              <text class="label">每组箭数</text>
              <view class="value-box">
                <text>{{ arrowsPerGroupOptions[arrowsPerGroupIndex] }}</text>
                <uni-icons type="arrowdown" size="16" color="#666"></uni-icons>
              </view>
            </view>
          </view>

          <view class="config-item">
            <text class="label">总计</text>
            <view class="value-box">
              <text>{{ totalArrowsDisplay }}</text>
            </view>
          </view>
        </template>
      </view>
    </view>

    <!-- 成绩输入区 -->
    <scroll-view 
      class="score-section" 
      :class="{ 
        'keyboard-active': showKeypad,
        'expanded': showKeypad || focusInScoreArea 
      }"
      scroll-y 
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      ref="scoreScrollView"
      @touchstart="handleScoreAreaTouch"
    >
      <view 
        class="score-group" 
        v-for="(group, gIndex) in scoreGroups" 
        :key="gIndex"
        :id="'group-' + gIndex"
      >
        <view class="group-header">
          <text>第 {{ gIndex+1 }} 组</text>
          <text class="subtotal">小计：{{ group.subtotal }}</text>
        </view>
        <view 
          class="grid-container" 
          :class="{ 'grid-12': currentArrowsPerGroup === 12 }"
          :style="getGridStyle()"
        >
          <view 
            class="score-cell"
            :class="{ 
              active: currentFocus.group === gIndex && currentFocus.index === sIndex,
              'cell-12': currentArrowsPerGroup === 12
            }"
            v-for="(score, sIndex) in group.scores"
            :key="sIndex"
            @click="setFocus(gIndex, sIndex)"
            :id="'cell-' + gIndex + '-' + sIndex"
          >
            <input
              :id="'input-' + gIndex + '-' + sIndex"
              class="score-input"
              v-model="group.scores[sIndex]"
              placeholder="0"
              placeholder-class="placeholder"
              :disabled="true"
              type="text"
              :cursor-spacing="0"
              :show-confirm-bar="false"
              :adjust-position="false"
            />
          </view>
        </view>
      </view>
      <!-- 底部留白，确保最后一组也能滚动到合适位置 -->
      <view class="bottom-spacer" v-if="showKeypad"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="action-bar" :class="{ 'hide-when-popup': showPopup, 'hide-when-keyboard': showKeypad }">
      <view class="total-display">
        <text class="total-label">总分：</text>
        <text class="total-value">{{ totalScore }}</text>
      </view>
      <view class="action-buttons">
        <button class="clear-btn" @click="clearAllScores">清空</button>
        <button class="save-btn" @click="saveRecord">保存记录</button>
      </view>
    </view>

    <!-- 紧凑型数字键盘 -->
    <view class="number-keypad compact-keypad" v-if="showKeypad">
      <view class="keyboard-header">
        <text class="current-position">
          第{{ currentFocus.group + 1 }}组 第{{ currentFocus.index + 1 }}箭
        </text>
        <text class="close-keyboard" @click="hideKeypad">完成</text>
      </view>
      <view class="keyboard-grid compact-grid">
        <view 
          v-for="(key, index) in keypadKeys" 
          :key="index" 
          class="keypad-key compact-key"
          :class="{ 
            backspace: key === '⌫',
            special: key === 'X',
            miss: key === 'M'
          }"
          @touchstart="handleKeyPress(key)"
        >
          <text v-if="key === '⌫'" class="backspace-icon">⌫</text>
          <text v-else-if="key === 'M'">M(0)</text>
          <text v-else>{{ key }}</text>
        </view>
      </view>
    </view>

    <!-- 配置选择弹窗 -->
    <uni-popup ref="popup" type="bottom" background-color="#fff" @change="handlePopupChange">
      <view class="popup-content">
        <view class="popup-header">
          <text class="title">{{ popupTitle }}</text>
          <uni-icons 
            type="close" 
            size="20" 
            color="#999" 
            @click="closePopup"
          ></uni-icons>
        </view>
        <scroll-view scroll-y class="options-container">
          <view 
            class="option-item" 
            v-for="(item, index) in popupOptions" 
            :key="index"
            :class="{active: tempIndex === index}"
            @click="handleOptionSelect(index)"
          >
            {{ item }}
          </view>
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 恢复记录弹窗 -->
    <uni-popup ref="restorePopup" type="center" background-color="#fff">
      <view class="restore-popup">
        <text class="restore-title">检测到未完成的记录</text>
        <text class="restore-desc">发现上次未保存的成绩记录，您希望：</text>
        <view class="restore-buttons">
          <button class="restore-btn continue-btn" @click="continueLastRecord">继续记分</button>
          <button class="restore-btn restart-btn" @click="startNewRecord">重新记分</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
const KEYPAD_VALUES = ['X', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', 'M', '⌫'];

export default {
  data() {
    return {
      // 配置项数据
      bowIndex: 0,
      bowTypes: ['反曲', '复合', '光弓', '美猎', '传统'],
      distIndex: 0,
      distances: ['10米', '18米', '30米', '50米', '70米'],
      targetSizeIndex: 0,
      targetSizes: ['40', '60', '80', '122'],
      targetTypeIndex: 0,
      targetTypes: ['半环', '全环'],
      
      // 新的箭数配置
      groupCountIndex: 0, // 默认1组
      groupCounts: ['1组', '2组', '3组', '4组', '5组', '6组', '8组', '10组', '12组'],
      arrowsPerGroupIndex: 1, // 默认6箭
      arrowsPerGroupOptions: ['3箭', '6箭', '12箭'],
      
      // 弹窗相关
      popupType: '',
      popupTitle: '',
      popupOptions: [],
      tempIndex: -1,
      showPopup: false,
      
      // 成绩数据
      scoreGroups: [],
      
      // 键盘相关
      showKeypad: false,
      currentFocus: { group: -1, index: -1 },
      keypadKeys: KEYPAD_VALUES,
      scrollTop: 0,
      lastScrollTop: 0,
      
      // UI状态
      focusInScoreArea: false,
      
      // 自动保存相关
      autoSaveTimer: null,
      isRestoredData: false,
      hasUnfinishedRecord: false,
      isInitializing: false
    }
  },
  computed: {
    currentGroupCount() {
      return parseInt(this.groupCounts[this.groupCountIndex].replace('组', ''));
    },
    currentArrowsPerGroup() {
      return parseInt(this.arrowsPerGroupOptions[this.arrowsPerGroupIndex].replace('箭', ''));
    },
    totalArrows() {
      return this.currentGroupCount * this.currentArrowsPerGroup;
    },
    totalArrowsDisplay() {
      return `${this.currentGroupCount}组，每组${this.currentArrowsPerGroup}箭，共${this.totalArrows}箭`;
    },
    totalScore() {
      return this.scoreGroups.reduce((sum, group) => sum + group.subtotal, 0);
    },
    compactConfigText() {
      return `${this.bowTypes[this.bowIndex]} · ${this.distances[this.distIndex]} · ${this.targetSizes[this.targetSizeIndex]}cm${this.targetTypes[this.targetTypeIndex]} · ${this.totalArrows}箭`;
    }
  },
  watch: {
    groupCountIndex() {
      if (!this.isRestoredData && !this.hasUnfinishedRecord && !this.isInitializing) {
        this.initScoreGroups();
        this.saveUserPreferences();
      }
    },
    arrowsPerGroupIndex() {
      if (!this.isRestoredData && !this.hasUnfinishedRecord && !this.isInitializing) {
        this.initScoreGroups();
        this.saveUserPreferences();
      }
    },
    bowIndex() {
      if (!this.isRestoredData && !this.isInitializing) {
        this.saveUserPreferences();
      }
    },
    distIndex() {
      if (!this.isRestoredData && !this.isInitializing) {
        this.saveUserPreferences();
      }
    },
    targetSizeIndex() {
      if (!this.isRestoredData && !this.isInitializing) {
        this.saveUserPreferences();
      }
    },
    targetTypeIndex() {
      if (!this.isRestoredData && !this.isInitializing) {
        this.saveUserPreferences();
      }
    },
    scoreGroups: {
      handler() {
        if (!this.isRestoredData && !this.isInitializing) {
          this.autoSaveCurrentRecord();
        }
      },
      deep: true
    }
  },
  onLoad() {
    this.isInitializing = true;
    this.loadUserPreferences();
    this.checkUnfinishedRecord();
  },
  onUnload() {
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer);
    }
  },
  onHide() {
    if (!this.isRestoredData && !this.isInitializing) {
      this.autoSaveCurrentRecord();
    }
  },
  mounted() {
    if (!this.hasUnfinishedRecord && !this.isRestoredData) {
      this.initScoreGroups();
    }
    this.isInitializing = false;
  },
  methods: {
    // 获取网格样式
    getGridStyle() {
      if (this.currentArrowsPerGroup === 12) {
        return { gridTemplateColumns: 'repeat(6, 1fr)' }; // 12箭时显示为6列2行
      } else if (this.currentArrowsPerGroup === 6) {
        return { gridTemplateColumns: 'repeat(6, 1fr)' }; // 6箭时显示为3列2行
      } else {
        return { gridTemplateColumns: 'repeat(3, 1fr)' }; // 3箭时显示为3列1行
      }
    },

    // 处理成绩区域点击
    handleScoreAreaTouch() {
      if (!this.focusInScoreArea) {
        this.focusInScoreArea = true;
      }
    },

    // 展开配置区域
    expandConfig() {
      this.focusInScoreArea = false;
      this.hideKeypad();
    },

    loadUserPreferences() {
      const preferences = uni.getStorageSync('userPreferences');
      if (preferences) {
        this.bowIndex = preferences.bowIndex || 0;
        this.distIndex = preferences.distIndex || 0;
        this.targetSizeIndex = preferences.targetSizeIndex || 0;
        this.targetTypeIndex = preferences.targetTypeIndex || 0;
        this.groupCountIndex = preferences.groupCountIndex || 0;
        this.arrowsPerGroupIndex = preferences.arrowsPerGroupIndex || 1;
      }
    },

    saveUserPreferences() {
      if (this.isInitializing) return;
      
      const preferences = {
        bowIndex: this.bowIndex,
        distIndex: this.distIndex,
        targetSizeIndex: this.targetSizeIndex,
        targetTypeIndex: this.targetTypeIndex,
        groupCountIndex: this.groupCountIndex,
        arrowsPerGroupIndex: this.arrowsPerGroupIndex
      };
      uni.setStorageSync('userPreferences', preferences);
    },

    checkUnfinishedRecord() {
      const unfinishedRecord = uni.getStorageSync('unfinishedRecord');
      if (unfinishedRecord && this.hasValidScores(unfinishedRecord.scoreGroups)) {
        this.hasUnfinishedRecord = true;
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.restorePopup.open();
          }, 100);
        });
      } else {
        uni.removeStorageSync('unfinishedRecord');
        this.hasUnfinishedRecord = false;
      }
    },

    hasValidScores(scoreGroups) {
      return scoreGroups && scoreGroups.some(group => 
        group.scores.some(score => score !== '' && score !== null && score !== undefined)
      );
    },

    continueLastRecord() {
      const unfinishedRecord = uni.getStorageSync('unfinishedRecord');
      if (unfinishedRecord) {
        this.isRestoredData = true;
        
        this.bowIndex = unfinishedRecord.bowIndex || 0;
        this.distIndex = unfinishedRecord.distIndex || 0;
        this.targetSizeIndex = unfinishedRecord.targetSizeIndex || 0;
        this.targetTypeIndex = unfinishedRecord.targetTypeIndex || 0;
        this.groupCountIndex = unfinishedRecord.groupCountIndex || 0;
        this.arrowsPerGroupIndex = unfinishedRecord.arrowsPerGroupIndex || 1;
        
        this.$forceUpdate();
        
        this.$nextTick(() => {
          this.scoreGroups = JSON.parse(JSON.stringify(unfinishedRecord.scoreGroups || []));
          
          this.scoreGroups.forEach((group, index) => {
            this.calcSubtotal(index);
          });
          
          this.isRestoredData = false;
          this.hasUnfinishedRecord = false;
          this.focusInScoreArea = true; // 恢复时直接进入成绩输入模式
          
          uni.showToast({
            title: '已恢复上次记录',
            icon: 'success'
          });
        });
      }
      this.$refs.restorePopup.close();
    },

    startNewRecord() {
      uni.removeStorageSync('unfinishedRecord');
      this.hasUnfinishedRecord = false;
      this.initScoreGroups();
      this.$refs.restorePopup.close();
      
      uni.showToast({
        title: '开始新记录',
        icon: 'success'
      });
    },

    autoSaveCurrentRecord() {
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
      }
      
      this.autoSaveTimer = setTimeout(() => {
        if (this.hasValidScores(this.scoreGroups)) {
          const unfinishedRecord = {
            bowIndex: this.bowIndex,
            distIndex: this.distIndex,
            targetSizeIndex: this.targetSizeIndex,
            targetTypeIndex: this.targetTypeIndex,
            groupCountIndex: this.groupCountIndex,
            arrowsPerGroupIndex: this.arrowsPerGroupIndex,
            scoreGroups: JSON.parse(JSON.stringify(this.scoreGroups)),
            timestamp: Date.now()
          };
          uni.setStorageSync('unfinishedRecord', unfinishedRecord);
        }
      }, 1000);
    },

    clearAllScores() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有成绩吗？',
        success: (res) => {
          if (res.confirm) {
            this.initScoreGroups();
            uni.removeStorageSync('unfinishedRecord');
            uni.showToast({
              title: '已清空所有成绩',
              icon: 'success'
            });
          }
        }
      });
    },

    showBowTypePopup() {
      this.focusInScoreArea = false;
      this.setupPopup('弓种选择', this.bowTypes, this.bowIndex);
    },
    showDistancePopup() {
      this.focusInScoreArea = false;
      this.setupPopup('距离选择', this.distances, this.distIndex);
    },
    showTargetSizePopup() {
      this.focusInScoreArea = false;
      this.setupPopup('靶纸尺寸', this.targetSizes, this.targetSizeIndex);
    },
    showTargetTypePopup() {
      this.focusInScoreArea = false;
      this.setupPopup('靶纸类型', this.targetTypes, this.targetTypeIndex);
    },
    showGroupCountPopup() {
      this.focusInScoreArea = false;
      this.setupPopup('组数选择', this.groupCounts, this.groupCountIndex);
    },
    showArrowsPerGroupPopup() {
      this.focusInScoreArea = false;
      this.setupPopup('每组箭数', this.arrowsPerGroupOptions, this.arrowsPerGroupIndex);
    },

    setupPopup(title, options, currentIndex) {
      this.popupTitle = title;
      this.popupOptions = options;
      this.tempIndex = currentIndex;
      this.$refs.popup.open();
    },

    handlePopupChange(e) {
      this.showPopup = e.show;
    },

    handleOptionSelect(index) {
      const mapping = {
        '弓种选择': 'bowIndex',
        '距离选择': 'distIndex',
        '靶纸尺寸': 'targetSizeIndex',
        '靶纸类型': 'targetTypeIndex',
        '组数选择': 'groupCountIndex',
        '每组箭数': 'arrowsPerGroupIndex'
      }
      if (mapping[this.popupTitle]) {
        this[mapping[this.popupTitle]] = index;
      }
      this.closePopup();
    },

    closePopup() {
      this.$refs.popup.close();
    },

    initScoreGroups() {
      this.scoreGroups = Array.from({length: this.currentGroupCount}, () => ({
        scores: Array(this.currentArrowsPerGroup).fill(''),
        subtotal: 0
      }));
      
      this.currentFocus = { group: -1, index: -1 };
      this.showKeypad = false;
      this.scrollTop = 0;
      this.lastScrollTop = 0;
    },

    setFocus(gIndex, sIndex) {
      this.focusInScoreArea = true;
      
      if (this.currentFocus.group === gIndex && this.currentFocus.index === sIndex) {
        this.showKeypad = !this.showKeypad;
        if (this.showKeypad) {
          this.$nextTick(() => {
            this.scrollToCurrentInput();
          });
        }
        return;
      }
      
      this.currentFocus = { group: gIndex, index: sIndex };
      this.showKeypad = true;
      
      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollToCurrentInput();
        }, 100);
      });
      
      uni.vibrateShort({
        type: 'light'
      });
    },

    scrollToCurrentInput() {
      if (this.currentFocus.group === -1 || this.currentFocus.index === -1) return;
      
      const query = uni.createSelectorQuery().in(this);
      const { group, index } = this.currentFocus;
      
      query.selectAll(`#cell-${group}-${index}, .score-section`).boundingClientRect((rects) => {
        if (rects && rects.length === 2) {
          const cellRect = rects[0];
          const scrollRect = rects[1];
          
          if (cellRect && scrollRect) {
            const keyboardHeight = 280; // 紧凑键盘高度
            const safeAreaHeight = 50;
            const visibleHeight = scrollRect.height - keyboardHeight - safeAreaHeight;
            
            const cellRelativeTop = cellRect.top - scrollRect.top + this.lastScrollTop;
            const targetPosition = visibleHeight * 0.3;
            const scrollOffset = cellRelativeTop - targetPosition;
          }
        }
      }).exec();
    },

    hideKeypad() {
      this.showKeypad = false;
      this.currentFocus = { group: -1, index: -1 };
    },

    handleKeyPress(key) {
      const { group, index } = this.currentFocus;
      if (group === -1 || index === -1) return;

      uni.vibrateShort({
        type: 'light'
      });

      if (key === '⌫') {
        this.handleBackspace();
        return;
      }

      let value = key;
      if (key === 'M') value = '0';
      if (key === 'X') value = 'X';

      this.$set(this.scoreGroups[group].scores, index, value);
      this.calcSubtotal(group);
      this.moveFocusForward();
    },

    handleBackspace() {
      const { group, index } = this.currentFocus;
      if (group === -1 || index === -1) return;

      this.$set(this.scoreGroups[group].scores, index, '');
      this.calcSubtotal(group);
      this.moveFocusBackward();
    },

    calcSubtotal(groupIndex) {
      const scores = this.scoreGroups[groupIndex].scores
      const subtotal = scores.reduce((sum, val) => {
        const numVal = val.toUpperCase() === 'X' ? 10 : Number(val) || 0
        return sum + Math.min(numVal, 10)
      }, 0);
      
      this.$set(this.scoreGroups[groupIndex], 'subtotal', subtotal);
    },

    moveFocusForward() {
      let { group, index } = this.currentFocus;
      const currentGroup = this.scoreGroups[group];
      
      if (index < currentGroup.scores.length - 1) {
        index++;
      } else {
        if (group < this.scoreGroups.length - 1) {
          group++;
          index = 0;
        } else {
          this.hideKeypad();
          return;
        }
      }
      
      this.currentFocus = { group, index };
      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollToCurrentInput();
        }, 50);
      });
    },

    moveFocusBackward() {
      let { group, index } = this.currentFocus;
      
      if (index > 0) {
        index--;
      } else {
        if (group > 0) {
          group--;
          index = this.scoreGroups[group].scores.length - 1;
        }
      }
      
      this.currentFocus = { group, index };
      this.$nextTick(() => {
        setTimeout(() => {
          this.scrollToCurrentInput();
        }, 50);
      });
    },

    async saveRecord() {
      const hasEmptyScores = this.scoreGroups.some(group => 
        group.scores.some(score => score === '' || score === null || score === undefined)
      );
      
      if (hasEmptyScores) {
        uni.showModal({
          title: '提示',
          content: '还有成绩未填写，确认保存吗？',
          success: (res) => {
            if (res.confirm) {
              this.doSaveRecord();
            }
          }
        });
        return;
      }
      
      this.doSaveRecord();
    },
    
    doSaveRecord() {
      const userId = getApp().globalData.userId || uni.getStorageSync('userId') || 'unknown';
      
      const record = {
        id: Date.now(),
        userId: userId,
        date: new Date().toISOString(),
        timestamp: Date.now(),
        config: {
          bowType: this.bowTypes[this.bowIndex],
          distance: this.distances[this.distIndex],
          target: `${this.targetSizes[this.targetSizeIndex]}cm-${this.targetTypes[this.targetTypeIndex]}`,
          totalArrows: this.totalArrows,
          groupCount: this.currentGroupCount,
          arrowsPerGroup: this.currentArrowsPerGroup
        },
        scores: this.scoreGroups.map(g => ({
          scores: [...g.scores],
          subtotal: g.subtotal
        })),
        total: this.totalScore
      }
      
      try {
        const history = uni.getStorageSync('trainingHistory') || []
        history.unshift(record)
        
        if (history.length > 100) {
          history.splice(100);
        }
        
        uni.setStorageSync('trainingHistory', history)
        uni.removeStorageSync('unfinishedRecord');
        
        uni.showToast({ 
          title: '保存成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('保存失败:', error);
        uni.showToast({
          title: '保存失败',
          icon: 'error'
        });
      }
    }
  }
}
</script>

<style lang="scss">
$primary-color: #4a8cff;
$border-color: #e5e5e5;
$group-bg: #ffffff;
$text-color: #333;
$text-light: #666;
$text-lighter: #999;

.record-container {
  padding: 20rpx;
  background-color: #f5f6fa;
  min-height: 100vh;
  box-sizing: border-box;
  padding-bottom: calc(120rpx + env(safe-area-inset-bottom));
}

.config-section {
  transition: all 0.3s ease;
  
  &.compact {
    margin-bottom: 10rpx;
  }
}

.config-card {
  background: white;
  border-radius: 16rpx;
  padding: 0 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.04);
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
}

.compact-config {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  
  .compact-text {
    font-size: 26rpx;
    color: $text-light;
    flex: 1;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.config-item {
  display: flex;
  align-items: center;
  padding: 32rpx 0;
  border-bottom: 1rpx solid $border-color;
  
  &:last-child {
    border-bottom: none;
  }
  
  .label {
    font-size: 28rpx;
    color: #666;
    margin-right: 40rpx;
    min-width: 80rpx;
  }
  
  .value-box {
    flex: 1;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    font-size: 32rpx;
    color: #333;
    
    text {
      margin-right: 16rpx;
    }
  }
  
  &.double {
    display: flex;
    justify-content: space-between;
    .half-item {
      width: 48%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      
      .label {
        font-size: 26rpx;
        min-width: auto;
        margin-right: 20rpx;
      }
      
      .value-box {
        font-size: 28rpx;
      }
    }
  }
}

.score-section {
  max-height: calc(100vh - 540rpx);
  margin-bottom: 20rpx;
  transition: all 0.3s ease;
  
  &.expanded {
    max-height: calc(100vh - 380rpx);
  }
  
  &.keyboard-active {
    max-height: calc(100vh - 480rpx);
  }
  
  &.expanded.keyboard-active {
    max-height: calc(100vh - 360rpx);
  }
}

.score-group {
  background: $group-bg;
  border-radius: 16rpx;
  margin: 20rpx 0;
  padding: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06);
  
  .group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 24rpx;
    font-size: 28rpx;
    
    .subtotal {
      color: $primary-color;
      font-weight: 600;
      font-size: 32rpx;
    }
  }
}

.grid-container {
  display: grid;
  gap: 15rpx;
  
  &.grid-12 {
    gap: 10rpx; // 12箭时间距更小
  }
}

.score-cell {
  position: relative;
  height: 100rpx;
  border-radius: 12rpx;
  background: #f8f9fa;
  border: 2rpx solid $border-color;
  transition: all 0.2s;
  
  &.cell-12 {
    height: 80rpx; // 12箭时高度更小
  }
  
  &.active {
    border-color: $primary-color;
    box-shadow: 0 0 8rpx rgba(74,140,255,0.3);
    background: rgba(74,140,255,0.05);
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.score-input {
  width: 100%;
  height: 100%;
  font-size: 36rpx;
  color: #333;
  text-align: center;
  padding: 0 10rpx;
  box-sizing: border-box;
  background: transparent;
  border: none;
  
  .cell-12 & {
    font-size: 32rpx; // 12箭时字体更小
  }
  
  &.placeholder {
    color: #c0c4cc;
    font-size: 28rpx;
  }
}

.bottom-spacer {
  height: 300rpx;
}

.action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: white;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.1);
  z-index: 999;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  transition: transform 0.3s ease;
  
  &.hide-when-popup,
  &.hide-when-keyboard {
    transform: translateY(100%);
  }
  
  .total-display {
    display: flex;
    align-items: baseline;
    
    .total-label {
      font-size: 32rpx;
      color: #666;
    }
    
    .total-value {
      font-size: 48rpx;
      color: $primary-color;
      font-weight: 600;
      margin-left: 16rpx;
    }
  }
  
  .action-buttons {
    display: flex;
    gap: 20rpx;
    
    .clear-btn {
      background: #999;
      color: white;
      border-radius: 50rpx;
      padding: 0 32rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 28rpx;
      
      &::after {
        border: none;
      }
    }
    
    .save-btn {
      background: $primary-color;
      color: white;
      border-radius: 50rpx;
      padding: 0 48rpx;
      height: 80rpx;
      line-height: 80rpx;
      font-size: 32rpx;
      
      &::after {
        border: none;
      }
    }
  }
}

// 紧凑型键盘样式
.compact-keypad {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #f5f5f5;
  box-shadow: 0 -4rpx 12rpx rgba(0,0,0,0.1);
  z-index: 1000;
  padding-bottom: env(safe-area-inset-bottom);
  
  .keyboard-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx 30rpx;
    background: white;
    border-bottom: 1rpx solid #e5e5e5;
    
    .current-position {
      font-size: 26rpx;
      color: #666;
    }
    
    .close-keyboard {
      font-size: 30rpx;
      color: $primary-color;
      font-weight: 500;
    }
  }
}

.compact-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10rpx;
  padding: 15rpx;
}

.compact-key {
  height: 70rpx;
  background: white;
  border-radius: 8rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  font-weight: 500;
  transition: all 0.1s;
  box-shadow: 0 2rpx 4rpx rgba(0,0,0,0.1);
  
  &:active {
    background: #e5e5e5;
    transform: scale(0.95);
  }
  
  &.backspace {
    background: #ff4d4f;
    color: white;
    
    &:active {
      background: #ff7875;
    }
    
    .backspace-icon {
      font-size: 28rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  &.special {
    background: #52c41a;
    color: white;
    
    &:active {
      background: #73d13d;
    }
  }
  
  &.miss {
    background: #007bff;
    color: white;
    
    &:active {
      background: #409eff;
    }
  }
}

.popup-content {
  padding: 40rpx;
  border-radius: 24rpx 24rpx 0 0;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
    
    .title {
      font-size: 36rpx;
      font-weight: 500;
      color: #333;
    }
  }
  
  .options-container {
    max-height: 50vh;
    padding-bottom: env(safe-area-inset-bottom);
  }
  
  .option-item {
    padding: 28rpx 32rpx;
    font-size: 32rpx;
    color: #666;
    border-radius: 8rpx;
    margin-bottom: 16rpx;
    transition: background-color 0.2s;
    
    &.active {
      background: rgba($primary-color, 0.1);
      color: $primary-color;
      font-weight: 500;
    }
    
    &:active {
      background-color: #f5f5f5;
    }
  }
}

.restore-popup {
  padding: 60rpx 40rpx;
  text-align: center;
  min-width: 600rpx;
  border-radius: 24rpx;
  
  .restore-title {
    display: block;
    font-size: 36rpx;
    font-weight: 600;
    color: $text-color;
    margin-bottom: 30rpx;
  }
  
  .restore-desc {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 50rpx;
    line-height: 1.5;
  }
  
  .restore-buttons {
    display: flex;
    gap: 20rpx;
    
    .restore-btn {
      flex: 1;
      height: 80rpx;
      border-radius: 40rpx;
      font-size: 30rpx;
      font-weight: 500;
      
      &::after {
        border: none;
      }
      
      &.continue-btn {
        background: $primary-color;
        color: white;
      }
      
      &.restart-btn {
        background: #f5f5f5;
        color: #666;
      }
    }
  }
}
</style>